<template>
    <view>
        <!-- <view class="posterView">
            <image class="imgbackground" :src="backgroundUrl" mode="widthFix"></image>
            <view class="card" v-if="showCard">
                <view class="left">
                    <view class="top">
                        <image class="avatar" :src="avatarUrl" mode=""></image>
                        <view class="wrapper">
                            <view class="name">
                                {{name}}
                            </view>
                            <view class="telephone">
                                电话：{{telephone}}
                            </view>
                        </view>
                    </view>
                    <view class="line">

                    </view>
                    <view class="bottom">
                        微信扫一扫或长按识别，了解更多
                    </view>
                </view>
                 <image class="right" :src="qrCodeUrl" mode=""></image>

            </view>
            <image v-else class="qrcode" :src="qrCodeUrl" mode=""></image>
        </view>

        <canvas class="canvasContainer" :canvas-id="CanvasID" :style="{ width: canvasWidth + 'rpx', height: canvasHeigth + 'rpx'}"></canvas> 	 -->
        <canvas :canvas-id="CanvasID" :style="{ width: canvasWidth + 'rpx', height: canvasHeigth + 'rpx'}"></canvas>
    </view>
</template>

<script>
    let onCanvasDuty = 0;
	
	import Config from "@/config.js"; // 系统参数
	
	// #ifdef APP-PLUS
	var plugin = uni.requireNativePlugin('Vnidev-DyPlugin-Core')
	const dyclientId = Config.tiktokClientKeyApp;
	// #endif
	
    export default {
        data() {
            return {
                canvasWidth: 620,
                canvasHeigth: 930,
                CanvasID: "posterId",
                tempFilePath: '',
                isIdleCanvas: true,
                freshEn: false,
                
				backgroundUrl:"",
				qrCodeUrl:"",
				avatarUrl:"",
				showCard:false,
				name:"",
				telephone: "",
				qrCodeSize: 150,
				qrCodeLeft: -1,
				qrCodeTop: -1,
            };
        },

        components: {},

        mounted() {

        },
        methods: {
            async getImageInfo({
            	imgSrc
            }) {
            	return new Promise((resolve, errs) => {
            		uni.getImageInfo({
            			src: imgSrc,
            			success: function(image) {
            				resolve(image);
            			},
            			fail(err) {
            				errs(err);
            			}
            		});
            	});
            },

            isIdle(){
                return this.isIdleCanvas
            },

            freshCanvas(posterObj){		
				if (this.isIdleCanvas){ 
					this.backgroundUrl = posterObj.backgroundUrl
					this.qrCodeUrl = posterObj.qrCodeUrl
					this.avatarUrl = posterObj.avatarUrl
					this.showCard = posterObj.showCard
					this.name = posterObj.name
					this.telephone = posterObj.telephone
					this.qrCodeSize = posterObj.qrCodeSize
					this.qrCodeLeft = posterObj.qrCodeLeft
					this.qrCodeTop = posterObj.qrCodeTop
					uni.showLoading({
					    mask: true,
					    title:'海报制作中'
					})
					this.OnCanvas()
				}                     
            },
			
            async OnCanvas() {
            	let _this = this

                console.log("start OnCanvas")
                _this.isIdleCanvas = false;

            	_this.ctx = uni.createCanvasContext(this.CanvasID, this);

                if (_this.backgroundUrl.length <= 0){
                    _this.isIdleCanvas = true;
                    uni.showModal({
                        title: '提示',
                        showCancel:false,
                        content: '找不到海报背景图，海报制作失败！',
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                            } else if (res.cancel) {
                                console.log('用户点击取消');
                            }
                        }
                    });
					uni.hideLoading()
                    return
                }
                if (_this.qrCodeUrl.length<=0){
                    _this.isIdleCanvas = true;
                    uni.showModal({
                        title: '提示',
                        showCancel:false,
                        content: '找不到二维码，海报制作失败！',
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                            } else if (res.cancel) {
                                console.log('用户点击取消');
                            }
                        }
                    });
					uni.hideLoading()
                    return
                }


                let _imgInfo = await _this.getImageInfo({
                	imgSrc: _this.backgroundUrl
                }); //背景图图

                _this.canvasWidth = 620
                _this.canvasHeigth = 620*_imgInfo.height/_imgInfo.width

            	var CanvasWidthPx = uni.upx2px(_this.canvasWidth); //canvas宽度
                var CanvasHeightPx = uni.upx2px(_this.canvasHeigth);

            	var QrSize = uni.upx2px(_this.qrCodeSize); //二维码或太阳码宽高

                var CanvasBg = "#ffffff"
                _this.ctx.setFillStyle(CanvasBg); //canvas背景颜色
                _this.ctx.fillRect(0, 0, CanvasWidthPx,CanvasHeightPx); //canvas画布大小

                if ( _this.backgroundUrl.length > 0){
                    //添加图片展示
                    _this.ctx.drawImage(_imgInfo.path, 0, 0, CanvasWidthPx, CanvasHeightPx);
                    //添加图片展示 end
                }


                //添加二维码
                if (_this.qrCodeUrl.length>0){
                    let _QrCode = await _this.getImageInfo({
                        imgSrc: _this.qrCodeUrl
                    }); //二维码或太阳码
                    var QrCodeY_rpx = _this.canvasHeigth - _this.qrCodeSize - 30
                    var QrCodeX_rpx = _this.canvasWidth - _this.qrCodeSize - 30

                    if (_this.qrCodeTop>=0){
                        QrCodeY_rpx = _this.qrCodeTop
                    }

                    if (_this.qrCodeLeft>=0){
                        QrCodeX_rpx = _this.qrCodeLeft
                    }

                    var QrCodeY = uni.upx2px(QrCodeY_rpx)
                    var QrCodeX = uni.upx2px(QrCodeX_rpx)

                    _this.ctx.save()
                    _this.ctx.beginPath()
                    _this.ctx.arc(QrCodeX+QrSize/2, QrCodeY+QrSize/2, QrSize/2, 0, 2 * Math.PI)
                    _this.ctx.clip()
                    _this.ctx.drawImage(_QrCode.path,QrCodeX,QrCodeY, QrSize, QrSize)
                    _this.ctx.restore()
                    //添加二维码 end
                }


            	//延迟后渲染至canvas上
            	setTimeout(function() {
            		_this.ctx.draw(true, (ret) => {
            			setTimeout(() => {
            				_this.getNewImage();
            			}, 1000)
            		});
            	}, 1000);
            },

            getNewImage(callback) {
            	let that = this;
            	uni.canvasToTempFilePath({
            		canvasId: that.CanvasID,
            		quality: 1,
                    success:(res)=>{
                        console.log("图片生成成功：",res.tempFilePath);
                        that.tempFilePath = res.tempFilePath
                        typeof callback == 'function' && callback();
                        that.$emit('success', res);
                    },
					fail:(err)=>{
						console.log("getNewImage err", err)
					},
            		complete: (res) => {
						console.log("getNewImage")
						uni.hideLoading()
                        that.isIdleCanvas = true
            		}
            	}, this);
            },

            // 保存海报到相册
            savePoster() {
            	let that = this
				// #ifdef APP-PLUS
				plugin.hasPhotoPerm({}, data => {
					console.log("getAlbumAuthorized", data)
					if (data.finished && data.write_photo && data.read_photo) {
						that.saveImg();
					} else {
						that.authConfirm()
					}
				});
				// #endif
				// #ifndef APP-PLUS
				uni.getSetting({
					success(res) {
						if (res.authSetting['scope.writePhotosAlbum']) {
							that.saveImg();
						} else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									that.saveImg();
								},
								fail() {
									that.authConfirm()
								}
							})
						} else {
							that.authConfirm()
						}
					}
				})
				// #endif
            	
            },
            // 授权拒绝后，再次授权提示弹窗
            authConfirm() {
            	let that = this
            	uni.showModal({
            		content: '检测到您没打开保存图片权限，是否去设置打开？',
            		confirmText: "确认",
            		cancelText: "取消",
            		success: function(res) {
            			if (res.confirm) {
            				uni.openSetting({
            					success(res) {
            						if (res.authSetting['scope.writePhotosAlbum']) {
            							that.saveImg();
            						} else {
            							uni.showToast({
            								title: '您没有授权，无法保存到相册',
            								icon: 'none'
            							})
            						}
            					}
            				})
            			} else {
            				uni.showToast({
            					title: '您没有授权，无法保存到相册',
            					icon: 'none'
            				})
            			}
            		}
            	});
            },

            // 图片保存到本地
            saveImg() {
            	let that = this;

            	if ((typeof that.tempFilePath == 'string')
                    && (that.tempFilePath.length > 0)
                    &&(that.isIdleCanvas)
                    &&(!that.freshEn)
                    ) {
            		that.saveImage();
            	} else {
                    if (that.isIdleCanvas){
                        that.OnCanvas();
                    }
                    uni.showModal({
                        title: '提示',
                        showCancel:false,
                        content: '海报制作中，请稍后重试！',
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                            } else if (res.cancel) {
                                console.log('用户点击取消');
                            }
                        }
                    });
            	}
            },

            saveImage() {
            	let that = this;
            	uni.getImageInfo({
            		src: that.tempFilePath,
            		success: function(image) {
            			console.log('图片信息：', JSON.stringify(image));
            			uni.saveImageToPhotosAlbum({
            				filePath: image.path,
            				success: function() {
            					console.log('save success');
            					that.$emit('close');
            					uni.showToast({
            						title: '图片保存成功',
            						icon: 'none',
            						duration: 2200
            					});
            				}
            			});
            		},
            		fail: function(res) {
            			console.log('saveImg:', res)
            		}
            	});
            },
        },


    };
</script>


<style lang="scss">
    .posterView{
        width: 620rpx;
        // height: 930rpx;
        position: relative;

        .imgbackground{
            width: 620rpx;
            // height: 930rpx;
            // position: absolute;
            // left: 0;
            // top: 0;
        }

        .qrcode{
            position: absolute;
            right: 30rpx;
            bottom: 30rpx;
            width: 120rpx;
            height: 120rpx;
            border-radius: 50%;
        }


        .card{
            width: 620rpx;
            height: 182rpx;
            background-color: #ffffff;
            position: absolute;
            left: 0;
            bottom: 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .left{
                margin-left: 30rpx;
                .top{
                    display: flex;
                    align-items: center;
                    .avatar{
                        width: 72rpx;
                        height: 72rpx;
                        border-radius: 50%;
                    }
                    .wrapper{
                        margin-left: 15rpx;
                        .name{
                            font-size: 28rpx;
                            font-weight: bold;
                            color: #333333;
                            margin-bottom: 15rpx;
                        }
                        .telephone{
                            font-size: 24rpx;
                            color: #999999;
                        }
                    }
                }
                .line{
                    width: 346rpx;
                    height: 1px;
                    background-color: #e8e8e8;
                    margin-top: 20rpx;
                    margin-bottom: 15rpx;
                }
                .bottom{
                    font-size: 20rpx;
                    letter-spacing: 1rpx;
                    color: #b3b3b3;
                }
            }
            .right{
                margin-right: 30rpx;
                width: 160rpx;
                height: 160rpx;
                border-radius: 50%;
            }
        }

    }
    .canvasContainer{
        opacity: 0;
        position: fixed;
        left: 0;
        top: -4000rpx;
        z-index: -999999;
    }

    .canvasContainer2{

    }
</style>
